package command

import (
	"net/textproto"
	"sort"
	"strings"
)

// Command - FreeSWITCH ESL 命令的基本接口
type Command interface {
	BuildCmd() string
	BuildMessage() string
}

var crlfToLF = strings.NewReplacer("\r\n", "\n")

// FormatHeaderString - Writes headers in a FreeSWITCH ESL friendly format. Converts headers containing \r\n to \n
func FormatHeaderString(headers textproto.MIMEHeader) string {
	var ws strings.Builder

	keys := make([]string, len(headers))
	i := 0
	for key := range headers {
		keys[i] = key
		i++
	}
	sort.Strings(keys)

	for _, key := range keys {
		for _, value := range headers[key] {
			value = crlfToLF.Replace(value)
			value = textproto.TrimString(value)
			ws.WriteString(key)
			ws.WriteString(": ")
			ws.WriteString(value)
			ws.WriteString("\r\n")
		}
	}
	// Remove the extra \r\n
	return ws.String()[:ws.Len()-2]
}
